package middleware

import (
	"net/http"
	"strings"
	"github.com/gin-gonic/gin"
	"encoding/json"
	"fmt"
	"gitee.com/ifinder/finder-ginutils/findergin/utils"
	"gitee.com/ifinder/gocomm/protocol/resp"
)

func RequestParamsToContext()  gin.HandlerFunc{
	return func(c *gin.Context) {
		content_type:= strings.ToLower(c.Request.Header.Get("Content-Type"))
		if http.MethodPost == strings.ToUpper(c.Request.Method) {
			requestData := make(map[string]interface{})
			if strings.Contains(content_type,"application/json"){
				// post json
				d, _ := c.GetRawData()
				/*if err := json.Unmarshal(d, &requestData); err == nil {
					//把数据放到 context中
					for k, v := range requestData {
						c.Set(k, v)
					}
				}*/

				dec:=json.NewDecoder(strings.NewReader(string(d)))
				dec.UseNumber()
				if err := dec.Decode(&requestData); err == nil {
					//把数据放到 context中
					for k, v := range requestData {
						c.Set(k, v)
					}
				}

			}else if strings.Contains(content_type,"application/x-www-form-urlencoded"){
				// post form
				c.Request.ParseForm()
				for k, v := range c.Request.Form  {
					c.Set(k, v[0])
				}
			}

		} else if http.MethodGet == strings.ToUpper(c.Request.Method) {

			c.Request.ParseForm()
			for k, v := range c.Request.Form {
				c.Set(k, v[0])
			}
		}
		c.Next()
	}
}


// 如果抛出异常，那么返回服务器内部错误
func ExceptionMiddleware()  gin.HandlerFunc {
	return func(c *gin.Context) {

		defer func() {
			if err:=recover();err!=nil{
				fmt.Println(err)
				utils.DoResponse(http.StatusInternalServerError,c,&resp.SimpleResponse{Result_code:resp.ERROR})
				c.Abort()
			}
		}()

		c.Next()
	}

}
